package com.example.yin.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.example.yin.common.R;
import com.example.yin.mapper.ConsumerMapper;
import com.example.yin.model.domain.Consumer;
import com.example.yin.service.FileService;
import com.example.yin.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;


@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private ConsumerMapper consumerMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //最大图片大小
    private final long maxFileSize=5*1024*1024;

    /**
     * 上传头像到OSS
     */
    public R uploadFileAvatar(MultipartFile file,int id) {

        // 工具类获取值
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        InputStream inputStream = null;
        try {
            // 创建OSS实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 判断文件大小
            long fileSize = file.getSize();
            if (fileSize > maxFileSize) {
                throw new RuntimeException("文件不能大于5MB");
            }

            // 把文件按照日期分类，获取当前日期
            String datePath = new DateTime().toString("yyyy-MM");
            // 获取上传文件的输入流
            inputStream = file.getInputStream();
            // 获取文件名称
            String originalFileName = file.getOriginalFilename();

            // 拼接日期和文件路径
            String fileName = originalFileName;

            // 判断文件是否存在
            boolean exists = ossClient.doesObjectExist(bucketName, fileName);
            if (exists) {
                // 如果文件已存在，则先删除原来的文件再进行覆盖
                ossClient.deleteObject(bucketName, fileName);
            }

            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(inputStream.available());
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            // 调用oss实例中的方法实现上传
            // 参数1： Bucket名称
            // 参数2： 上传到oss文件路径和文件名称 /aa/bb/1.jpg
            // 参数3： 上传文件的输入流
            ossClient.putObject(bucketName, fileName, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            // 把上传后文件路径返回，需要把上传到阿里云oss路径手动拼接出来
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;


//            //redis缓存(已经舍弃)
//            /**
//             * 1 根据id查询用户
//             * 2 拷贝用户 set修改
//             * 3 修改接口
//             */
//            // url保存到数据库
//            Consumer consumer = consumerMapper.selectById(id);//生成url后，更新用户信息，保存url头像
//            consumer.setAvator(url);
//            consumer.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
//            consumerMapper.updateById(consumer);
//
//            // 保存到本地项目img
//            URL urlObject = new URL(url);
//            String imageBase64Str = Base64Utils.encodeImgageToBase64(urlObject);//base64格式的图片
//            //放置在E:\music_website\music-website\img
//            String localImageAddr="E:\\music_website\\music-website\\img";
//            Base64Utils.decodeBase64ToImage(imageBase64Str,localImageAddr,fileName);
//
//            // redis缓存本地url地址
//            String avatorKey=bucketName+"|"+id;
//            String localUrl=localImageAddr+"\\"+fileName;
//            redisTemplate.opsForValue().set(avatorKey,localUrl);

            //注意修改数据库的用户Pic的地址
            Consumer consumer = consumerMapper.selectById(id);
            consumer.setAvator(url);
            consumerMapper.updateById(consumer);
            if(StringUtils.isNotBlank(url)){
                return R.success("上传成功",url);
            }else {
                return R.success("上传失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param filenameExtension 文件后缀
     * @return String
     */
    public static String getcontentType(String filenameExtension) {
        if ("bmp".equalsIgnoreCase(filenameExtension)) {
            return "image/bmp";
        }
        if ("gif".equalsIgnoreCase(filenameExtension)) {
            return "image/gif";
        }
        if ("jpeg".equalsIgnoreCase(filenameExtension) || filenameExtension.equalsIgnoreCase("jpg")
                || "png".equalsIgnoreCase(filenameExtension)) {
            return "image/jpeg";
        }
        if ("html".equalsIgnoreCase(filenameExtension)) {
            return "text/html";
        }
        if ("txt".equalsIgnoreCase(filenameExtension)) {
            return "text/plain";
        }
        if ("vsd".equalsIgnoreCase(filenameExtension)) {
            return "application/vnd.visio";
        }
        if ("pptx".equalsIgnoreCase(filenameExtension) || filenameExtension.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if ("docx".equalsIgnoreCase(filenameExtension) || filenameExtension.equalsIgnoreCase("doc")) {
            return "application/msword";
        }
        if ("xml".equalsIgnoreCase(filenameExtension)) {
            return "text/xml";
        }
        return "application/octet-stream";
    }



}
